package com.base.util

import android.content.DialogInterface
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

fun AppCompatActivity.dialog(message: CharSequence?, isFinish: Boolean = false) {
    if (isFinishing || isDestroyed) return
    val alertDialogBuilder = AlertDialog.Builder(this)
        .setTitle("温馨提示")
        .setMessage(message)
        .setCancelable(!isFinish)
        .setPositiveButton("确 定") { dialog, _ ->
            dialog?.dismiss()
            if (isFinish) {
                finish()
            }
        }
    runOnUiThread { alertDialogBuilder.show() }
}

fun AppCompatActivity.alert(
    content: CharSequence?,
    nextListener: DialogInterface.OnClickListener?,
    outsideCancel: Boolean = true
) {
    alert(content, "确 定", nextListener, "", null, outsideCancel)
}

fun AppCompatActivity.alert(
    content: CharSequence?,
    nextText: String?, nextListener: DialogInterface.OnClickListener?,
    cancelText: String?, cancelListener: DialogInterface.OnClickListener?,
    outsideCancel: Boolean = true
) {
    if (isFinishing || isDestroyed) return
    val alertDialogBuilder = AlertDialog.Builder(this)
        .setTitle("温馨提示")
        .setMessage(content)
        .setCancelable(outsideCancel)
    if (null != nextListener)
        alertDialogBuilder.setPositiveButton(nextText, nextListener)
    if (null != cancelListener)
        alertDialogBuilder.setNegativeButton(cancelText, cancelListener)
    runOnUiThread { alertDialogBuilder.show() }
}

//Fragment
fun Fragment.dialog(message: CharSequence?, isFinish: Boolean = false) {
    val act = activity ?: return
    if (act.isFinishing || act.isDestroyed) return
    val alertDialogBuilder = AlertDialog.Builder(act)
        .setTitle("温馨提示")
        .setMessage(message)
        .setCancelable(!isFinish)
        .setPositiveButton("确 定") { dialog, _ ->
            dialog?.dismiss()
            if (isFinish) {
                act.finish()
            }
        }
    act.runOnUiThread { alertDialogBuilder.show() }
}

fun Fragment.alert(
    content: CharSequence?,
    nextListener: DialogInterface.OnClickListener?,
    outsideCancel: Boolean
) {
    alert(content, "确 定", nextListener, "", null, outsideCancel)
}

fun Fragment.alert(
    content: CharSequence?, nextText: String?, nextListener: DialogInterface.OnClickListener?,
    cancelText: String?, cancelListener: DialogInterface.OnClickListener?, outsideCancel: Boolean
) {
    val act = activity ?: return
    if (act.isFinishing || act.isDestroyed) return
    val alertDialogBuilder = AlertDialog.Builder(act)
        .setTitle("温馨提示")
        .setMessage(content)
        .setCancelable(outsideCancel)
    if (null != nextListener)
        alertDialogBuilder.setPositiveButton(nextText, nextListener)
    if (null != cancelListener)
        alertDialogBuilder.setNegativeButton(cancelText, cancelListener)
    act.runOnUiThread { alertDialogBuilder.show() }
}